package com.jianhua.backend.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jianhua.backend.domain.dto.DishesDto;
import com.jianhua.backend.domain.entity.Categories;
import com.jianhua.backend.domain.entity.Dishes;
import com.jianhua.backend.domain.vo.PageVo;
import com.jianhua.backend.mapper.CategoriesMapper;
import com.jianhua.backend.mapper.DishesMapper;
import com.jianhua.backend.service.DishesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 存储所有菜品详细信息，包括营养成分等 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-02
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {

    @Autowired
    private DishesMapper dishesMapper;

    @Autowired
    private CategoriesMapper categoriesMapper;

    @Override
    public PageVo<Dishes> listDishes(DishesDto dishesDto) {
        Page<Dishes> page = new Page<>(dishesDto.getPage(), dishesDto.getSize());
        LambdaQueryWrapper<Dishes> wrapper = new LambdaQueryWrapper<>();
        if(dishesDto.getStatus() != null){
            wrapper.eq(Dishes::getStatus, dishesDto.getStatus());
        }
        if(dishesDto.getCategory_name() != null){
            LambdaQueryWrapper<Categories> categoryWrapper = new LambdaQueryWrapper<>();
            categoryWrapper.eq(Categories::getCategoryName, dishesDto.getCategory_name());
            Categories categories = categoriesMapper.selectOne(categoryWrapper);
            wrapper.eq(Dishes::getCategoryId, categories.getCategoryId());
        }
        if(dishesDto.getIs_halal() != null){
            wrapper.eq(Dishes::getIsHalal, dishesDto.getIs_halal());
        }
        if(dishesDto.getIs_hot() != null){
            wrapper.eq(Dishes::getIsHot, dishesDto.getIs_hot());
        }
        Page<Dishes> paged = page(page, wrapper);
        // 获取总记录数
        long total = page.getTotal();
        // 将总记录数转换为整型
        Integer count = Integer.valueOf((int) total);
        List<Dishes> records = paged.getRecords();
        return new PageVo<>(count, records);
    }

    @Override
    public void updateDishes(Dishes dishes) {
        int i = dishesMapper.updateById(dishes);
        if(i < 0){
            //todo: 抛出修改失败异常
        }
    }

    @Override
    public void deleteDishes(Integer id) {
        int i = dishesMapper.deleteById(id);
        if(i < 0){
            //todo: 抛出删除失败异常
        }
    }
}
